package ynu.edu.Service;

import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import ynu.edu.Util.PropertiesUtil;

import java.util.Properties;

@Service
public class FoxToken {
    @Value("${fbox.client_id}")
    private String clientId;

    @Value("${fbox.client_secret}")
    private String clientSecret;

    @Value("${fbox.token_url}")
    private String tokenUrl;

    @Resource
    private PropertiesUtil propertiesUtil;

    private String accessToken;
    private long tokenExpiryTime;

    public String getAccessToken() {
        Properties properties = propertiesUtil.loadProperties();
        String storedAccessToken = properties.getProperty("fox_access_token");
        String storedExpiryTime = properties.getProperty("fox_expires_in");

        if (storedAccessToken != null && storedExpiryTime != null) {
            long expiryTime = Long.parseLong(storedExpiryTime);
            if (System.currentTimeMillis() < expiryTime) {
                accessToken = storedAccessToken;
                tokenExpiryTime = expiryTime;
                return accessToken;
            }
        }

        fetchAccessToken();
        return accessToken;
    }

    private void fetchAccessToken() {
        RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("scope", "fbox");
        map.add("client_id", clientId);
        map.add("client_secret", clientSecret);
        map.add("grant_type", "client_credentials");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        String response = restTemplate.postForObject(tokenUrl, request, String.class);
        System.out.println("请求foxtoken");
        // 解析 JSON 响应
        com.fasterxml.jackson.databind.ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        try {
            com.fasterxml.jackson.databind.JsonNode rootNode = objectMapper.readTree(response);
            accessToken = rootNode.path("access_token").asText();
            int expiresIn = rootNode.path("expires_in").asInt();
            tokenExpiryTime = System.currentTimeMillis() + (expiresIn * 1000L) - 60000; // 提前1分钟过期

            // 更新 properties 文件
            Properties properties = propertiesUtil.loadProperties();
            properties.setProperty("fox_access_token", accessToken);
            properties.setProperty("fox_expires_in", String.valueOf(tokenExpiryTime));
            propertiesUtil.saveProperties(properties);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
